package com.bolun998300.personal_blog_springboot.controller.background;

import java.util.Date;
import java.util.HashMap;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;

import com.bolun998300.personal_blog_springboot.pojo.Link;
import com.bolun998300.personal_blog_springboot.service.LinkService;

@RestController
public class LinkController {
	@Autowired
	private LinkService linkService;
	
	@GetMapping("/links")
	public List<Link> list(){
		return linkService.list();
	}
	
	@GetMapping("/links/listByPage")
	public HashMap<String,Object> getLinkByPage(int page,int limit){
		Page<Link> pageFromJPA = linkService.listByPage(page, limit);
		HashMap<String,Object> map = new HashMap<>();
		map.put("code",0);
        map.put("msg","");
        map.put("count",pageFromJPA.getTotalElements());
        map.put("data",pageFromJPA.getContent());
        return map;
	}
	
	@DeleteMapping("/links/{id}")
	public String delete(@PathVariable int id) {
		linkService.delete(id);
		return "";
	}
	
	@GetMapping("/links/{id}")
	public Link get(@PathVariable int id) {
		return linkService.get(id);
	}

	@PostMapping("/links")
	public Object save(@RequestBody Link bean){
		bean.setOrderNo(1);
		bean.setCreateTime(new Date());
		linkService.save(bean);
		return "";
	}

	@PutMapping("/links")
	public Object update(@RequestBody Link bean){
		Link beanTemp = linkService.get(bean.getId());
		beanTemp.setLinkName(bean.getLinkName());
		beanTemp.setLinkUrl(bean.getLinkUrl());
		beanTemp.setUpdateTime(new Date());
		linkService.update(beanTemp);
		return "";
	}

}
